package cn.silver.module.system.service.impl;

import cn.silver.framework.core.exception.ServiceException;
import cn.silver.framework.mybatis.service.impl.DataServiceImpl;
import cn.silver.module.system.domain.SysPost;
import cn.silver.module.system.domain.SysUserPost;
import cn.silver.module.system.mapper.SysPostMapper;
import cn.silver.module.system.mapper.SysUserPostMapper;
import cn.silver.module.system.bean.PostBean;
import cn.silver.module.system.param.PostParam;
import cn.silver.module.system.service.ISysPostService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;

/**
 * 岗位信息 服务层处理
 *
 * @author Silver Zhou
 */
@Service
@RequiredArgsConstructor
public class SysPostServiceImpl extends DataServiceImpl<SysPostMapper, SysPost, PostParam, PostBean> implements ISysPostService {

    private final SysUserPostMapper userPostMapper;

    /**
     * 通过岗位ID查询岗位使用数量
     *
     * @param postId 岗位ID
     * @return 结果
     */
    @Override
    public Long countUserPostById(String postId) {
        return userPostMapper.selectCount(new LambdaQueryWrapper<SysUserPost>().eq(SysUserPost::getPostId, postId));
    }

    /**
     * 删除岗位信息
     *
     * @param postId 岗位ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public boolean delete(String postId) {
        SysPost post = this.baseMapper.selectById(postId);
        if (countUserPostById(postId) > 0) {
            throw new ServiceException(String.format("%1$s已分配，不能删除!", post.getName()));
        }
        return SqlHelper.retBool(baseMapper.deleteById(postId));
    }

    /**
     * 批量删除岗位信息
     *
     * @param postIds 需要删除的岗位ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void deleteBatch(Collection<String> postIds) {
//        List<SysPost> posts = this.baseMapper.selectBatchIds(postIds);
        for (String postId : postIds) {
            SysPost post = baseMapper.selectById(postId);
            if (countUserPostById(postId) > 0) {
                throw new ServiceException(String.format("%1$s已分配，不能删除!", post.getName()));
            }
        }
        baseMapper.deleteByIds(postIds);
    }
}
